import {useCompanyListRef} from "@/composition/billSys/useAccount.js";
import {
  addCompanyBill, addCompanyBillCategory,
  deleteCompanyBill, deleteCompanyBillCategory,
  getCompanyBillCategory, getCompanyBillHistory,
  getCompanyBills,
  updateCompanyBill
} from "@/api/bill/company/api.js";
import SafeCalc from "@/utils/bignumberjs.js";
import {getTodayAndMonthZeroTime} from "@/utils/index.js";

// -----------------------------------------------------------1---------------------------------------------------------------------------------------
// 公司账单数据
const companyBill = ref({});

const initCompanyBill = async () => {
  let companyList = useCompanyListRef();
  watchEffect(async () => {
    if (companyList.value.length === 0) {
      return;
    }
    // 遍历用户公司列表 然后查看是否有新公司 然后获取公司的账单写入
    let companyBillTemp = {...companyBill.value};
    for (let i = 0; i < companyList.value.length; i++) {
      let item = companyList.value[i];
      if (companyBill.value[item.companyId]) {
        continue;
      }
      let billList = await getCompanyBills(localStorage['id'], item.companyId);
      companyBillTemp[item.companyId] = billList.bills.map(item => {
        return {
          id: item.id,
          category: item.category.toString(),
          amount: item.amount,
          remark: item.remark,
          createTime: Number(item.create_time),
          isComplete: item.is_complete,
          isDelete: item.is_delete,
          creatorId: item.creator_id,
          billTime: Number(item.bill_time),
        };
      }).sort((a, b) => b.createTime - a.createTime);
    }
    companyBill.value = companyBillTemp;
  });
};

export const useCompanyBillRef = () => {
  return companyBill;
};

export const getCompanyBill = (companyId) => {
  return companyBill.value[companyId];
};

export const setCompanyBill = (companyId, billList) => {
  companyBill.value[companyId] = billList;
};

// 获取一个响应式对象代表当前公司的账单类型 并且使用一个缓存重读调用返回同一个响应式对象
const companyBillRefCache = {};
export const useCompanyBillRefById = (companyId) => {
  if (companyBillRefCache[companyId]) {
    return companyBillRefCache[companyId];
  }
  let billList = ref([]);
  watch(() => companyBill.value, (newVal) => {
    if (!newVal[companyId]) {
      return;
    }
    billList.value = [...newVal[companyId]];
  }, {immediate: true, deep: true});
  companyBillRefCache[companyId] = billList;
  return billList;
};

// 删除账单
export const useCompanyBillDelete = async (billId, companyId) => {
  await deleteCompanyBill(localStorage['id'], companyId, billId);
  let bill = companyBill.value[companyId].find(item => item.id === billId);
  if (bill) {
    bill.isDelete = 1;
  }
};

// 添加账单
// todo 新增billTime
export const useCompanyBillAdd = async (companyId, category, remark, amount, isComplete, billTime) => {
  let bill = (await addCompanyBill(localStorage['id'], companyId, category, remark, amount, isComplete, billTime)).bill;
  if (companyBill.value[companyId]) {
    companyBill.value[companyId] =  [{
      id: bill.id,
      category: bill.category,
      amount: bill.amount,
      remark: bill.remark,
      createTime: Number(bill.create_time),
      isComplete: bill.is_complete,
      isDelete: bill.is_delete,
      creatorId: Number(bill.creator_id),
      billTime: Number(bill.bill_time)
    }, ...companyBill.value[companyId]];
  }
};

// 修改账单
// todo 新增billTime
export const useCompanyBillUpdate = async (billId, companyId, category, remark, amount, isComplete, billTime) => {
  let bill = (await updateCompanyBill(localStorage['id'], companyId, billId, category, remark, amount, isComplete, billTime)).bill;
  let billList = [...companyBill.value[companyId]];
  let index = billList.findIndex(item => item.id === billId);
  if (index !== -1) {
    billList[index] = {
      id: bill.id,
      category: bill.category,
      amount: bill.amount,
      remark: bill.remark,
      createTime: Number(bill.create_time),
      isComplete: bill.is_complete,
      isDelete: bill.is_delete,
      creatorId: Number(bill.creator_id),
      billTime: Number(bill.bill_time)
    };
    billList.sort((a, b) => b.createTime - a.createTime);
    companyBill.value[companyId] = billList;
  }
};

// 获取账单的历史修改数据
export const useCompanyBillHistory = async (billId, companyId) => {
  let billHistory = (await getCompanyBillHistory(localStorage['id'], companyId, billId)).billHistory;
  let list = billHistory.map(item => {
    return {
      id: item.id,
      category: item.category.toString(),
      amount: item.amount,
      remark: item.remark,
      createTime: Number(item.create_time),
      isComplete: item.is_complete,
      isDelete: item.is_delete,
      creatorId: item.creator_id,
      billTime: Number(item.bill_time)
    };
  });
  return list.sort((a, b) => b.createTime - a.createTime);
};

initCompanyBill();

// -----------------------------------------------------------2---------------------------------------------------------------------------------------

// 公司账单分类数据
const companyBillCategory = ref({});
const companyAllBillCategory = ref({});

const initCompanyBillCategory = async () => {
  let companyList = useCompanyListRef();
  let times = 0;
  watchEffect(async () => {
    if (companyList.value.length === 0) {
      return;
    }
    let companyBillCategoryTemp = {...companyBillCategory.value};
    let billCategoryListTemp = {...companyAllBillCategory.value};
    // 遍历用户公司列表 然后查看是否有新公司 然后获取公司的账单类型写入
    for (let i = 0; i < companyList.value.length; i++) {
      let item = companyList.value[i];
      if (companyBillCategory.value[item.companyId]) {
        continue;
      }
      let billCategoryList = await getCompanyBillCategory(localStorage['id'], item.companyId);
      companyBillCategoryTemp[item.companyId] = billCategoryList.categories.map(it => {
        // 更新公司类型的时候同时更新全部类型的数据
        let res = {
          id: it.id,
          name: it.name,
          isOut: it.is_out
        };
        billCategoryListTemp[it.id] = res;
        return res;
      });
    }
    if (Object.keys(companyBillCategoryTemp).length !== Object.keys(companyBillCategory.value).length) {
      companyBillCategory.value = companyBillCategoryTemp;
    }
    if (Object.keys(billCategoryListTemp).length !== Object.keys(companyAllBillCategory.value).length) {
      companyAllBillCategory.value = billCategoryListTemp;
    }
  });
};

export const useCompanyBillCategoryRef = () => {
  return companyBillCategory;
};

export const getCompanyBillCategoryNow = (companyId) => {
  return companyBillCategory.value[companyId];
};

export const setCompanyBillCategoryNow = (companyId, billCategoryList) => {
  companyBillCategory.value[companyId] = billCategoryList;
};

export const useCompanyAllBillCategoryRef = () => {
  return companyAllBillCategory;
};

// 获取一个响应式对象代表当前公司的账单类型 并且进行一个缓存重复调用这个函数指挥返回同一个响应式对象
const companyBillCategoryRefCache = {};
export const useCompanyBillCategoryRefById = (companyId) => {
  if (companyBillCategoryRefCache[companyId]) {
    return companyBillCategoryRefCache[companyId];
  }
  let resRef = ref({});
  watch(() => companyBillCategory.value, () => {
    if (!companyBillCategory.value[companyId]) {
      return;
    }
    let obj = {};
    companyBillCategory.value[companyId].forEach(item => {
      obj[item.id] = item;
    });
    resRef.value = obj;
  }, {immediate: true, deep: true});
  companyBillCategoryRefCache[companyId] = resRef;
  return resRef;
};

// 删除公司账单分类
export const useCompanyBillCategoryDelete = async (companyId, categoryId) => {
  await deleteCompanyBillCategory(localStorage['id'], companyId, categoryId);
  // 更新所有公司的账单分类
  let allCategory = {...companyAllBillCategory.value};
  delete allCategory[categoryId];
  companyAllBillCategory.value = allCategory;
  // 更新当前公司的账单分类
  let companyCategory = [...companyBillCategory.value[companyId]];
  companyCategory = companyCategory.filter(item => item.id !== categoryId);
  companyBillCategory.value[companyId] = companyCategory;
};

// 新增公司账单分类
export const useCompanyBillCategoryAdd = async (companyId, categoryName, isOut) => {
  let categoryNew = (await addCompanyBillCategory(localStorage['id'], companyId, categoryName, isOut)).category;
 // 更新所有公司的账单分类
  let allCategory = {...companyAllBillCategory.value};
  allCategory[categoryNew.id] = {
    id: categoryNew.id,
    name: categoryNew.name,
    isOut: categoryNew.is_out
  };
  companyAllBillCategory.value = allCategory;
  // 更新当前公司的账单分类
  let companyCategory = [...companyBillCategory.value[companyId]];
  companyCategory = [...companyCategory, {
    id: categoryNew.id,
    name: categoryNew.name,
    isOut: categoryNew.is_out
  }];
  companyBillCategory.value[companyId] = companyCategory;
  return categoryNew;
};

initCompanyBillCategory();


// -----------------------------------------------------------3---------------------------------------------------------------------------------------
// 公司支出收入数据
// {
//   companyId: {
//     monthIn: '',
//     monthOut: ''
//   }
// }
// 公司工作台展示的信息
const companyData = ref({});

watchEffect(() => {
  if (Object.keys(companyBill.value).length === 0) {
    return;
  }
  // 遍历计算出公司的月收入和支出
  for (let key in companyBill.value) {
    let companyId = key;
    // 没有该公司的类型 返回
    if (!companyBillCategory.value[companyId]) {
      return;
    }
    let billList = companyBill.value[companyId];
    let monthIn = 0;
    let monthOut = 0;
    let {month} = getTodayAndMonthZeroTime();
    for (let i = 0; i < billList.length; i++) {
      let item = billList[i];
      if (item.createTime < month) {
        continue;
      }
      if (companyAllBillCategory.value[item.category] && companyAllBillCategory.value[item.category].isOut === 0) {
        monthIn = SafeCalc.add(monthIn, item.amount);
      }
      if (companyAllBillCategory.value[item.category] && companyAllBillCategory.value[item.category].isOut === 1) {
        monthOut = SafeCalc.add(monthOut, item.amount);
      }
    }
    companyData.value[companyId] = {
      monthIn,
      monthOut
    };
  }
});

export const getCompanyDataRef = (companyId) => {
  return companyData;
};
